package com.ithuameng.admin.app.system.service.impl;

import com.ithuameng.admin.app.system.model.User;
import com.ithuameng.admin.app.system.service.IMenuService;
import com.ithuameng.admin.app.system.service.IPermissionService;
import com.ithuameng.admin.app.system.service.IRoleService;
import com.ithuameng.admin.constants.CommonConstants;
import com.ithuameng.admin.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service("ss")
public class PermissionServiceImpl implements IPermissionService {

    /**
     * 所有权限标识
     */
    private static final String ALL_PERMISSION = "*:*:*";

    @Resource
    private IRoleService roleService;

    @Resource
    private IMenuService menuService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Set<String> getRolePermission(Long userId) {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (User.ADMIN_ID == userId) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(userId));
        }
        return roles;
    }

    @Override
    public Set<String> getMenuPermission(Long userId) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (User.ADMIN_ID == userId) {
            perms.add("*:*:*");
        } else {
            perms.addAll(menuService.selectMenuPermsByUserId(userId));
        }
        return perms;
    }

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    @Override
    public boolean hasPermi(String permission) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        Long userId = SecurityUtils.getUserId();
        // 如果查询不到说明未登录
        if (userId == null) {
            return false;
        }
        // 按钮如果查询不到说明没有权限
        String ps = stringRedisTemplate.opsForValue().get(CommonConstants.PERMESSION_PREFIX + Long.toString(userId));
        if (StringUtils.isBlank(ps)) {
            Set<String> menuPermissions = getMenuPermission(userId);
            if (menuPermissions != null && menuPermissions.size() > 0) {
                ps = StringUtils.join(menuPermissions, ",");
                stringRedisTemplate.opsForValue().set(CommonConstants.PERMESSION_PREFIX + Long.toString(userId),
                        ps, 2, TimeUnit.HOURS);
            }
        }
        if (StringUtils.isBlank(ps)) {
            return false;
        }
        // 判断是否包含权限
        return ps.contains(ALL_PERMISSION) || ps.contains(StringUtils.trim(permission));
    }
}
